

<!DOCTYPE html>
<html lang="zh-CN" data-default-color-scheme=auto>



<head>
  <meta charset="UTF-8">
  <link rel="apple-touch-icon" sizes="76x76" href="/img/favicon.png">
  <link rel="icon" href="/img/favicon.png">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=5.0, shrink-to-fit=no">
  <meta http-equiv="x-ua-compatible" content="ie=edge">
  
  <meta name="theme-color" content="#2f4154">
  <meta name="author" content="Cheney">
  <meta name="keywords" content="Coding">
  
    <meta name="description" content="通过如下方法产生一指令序列，共 320 条指令。计算并输出下述各种算法在不同内存页块(页块个数范围:8-32)下的命中率。">
<meta property="og:type" content="article">
<meta property="og:title" content="请求分页系统中的置换算法(FIFO、LRU、Optimal)">
<meta property="og:url" content="https://cheney822.gitee.io/2021/05/05/%E6%93%8D%E4%BD%9C%E7%B3%BB%E7%BB%9F__%E8%AF%B7%E6%B1%82%E5%88%86%E9%A1%B5%E7%B3%BB%E7%BB%9F%E4%B8%AD%E7%9A%84%E7%BD%AE%E6%8D%A2%E7%AE%97%E6%B3%95(FIFO%E3%80%81LRU%E3%80%81Optimal)/index.html">
<meta property="og:site_name" content="Cheney blog">
<meta property="og:description" content="通过如下方法产生一指令序列，共 320 条指令。计算并输出下述各种算法在不同内存页块(页块个数范围:8-32)下的命中率。">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://imgbed.cheney.cc/picgo/20210506173120425.png">
<meta property="og:image" content="https://imgbed.cheney.cc/picgo/20210506173024754.png">
<meta property="article:published_time" content="2021-05-05T00:22:00.000Z">
<meta property="article:modified_time" content="2022-04-05T13:14:29.887Z">
<meta property="article:author" content="Cheney">
<meta property="article:tag" content="算法">
<meta property="article:tag" content="C语言">
<meta name="twitter:card" content="summary_large_image">
<meta name="twitter:image" content="https://imgbed.cheney.cc/picgo/20210506173120425.png">
  
  
  <title>请求分页系统中的置换算法(FIFO、LRU、Optimal) - Cheney blog</title>

  <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4/dist/css/bootstrap.min.css" />


  <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/github-markdown-css@4/github-markdown.min.css" />
  <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/hint.css@2/hint.min.css" />

  
    
    
      
      <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/highlight.js@10/styles/github-gist.min.css" />
    
  

  
    <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@3/dist/jquery.fancybox.min.css" />
  


<!-- 主题依赖的图标库，不要自行修改 -->

<link rel="stylesheet" href="//at.alicdn.com/t/font_1749284_ba1fz6golrf.css">



<link rel="stylesheet" href="//at.alicdn.com/t/font_1736178_lbnruvf0jn.css">


<link  rel="stylesheet" href="/css/main.css" />

<!-- 自定义样式保持在最底部 -->


  <script id="fluid-configs">
    var Fluid = window.Fluid || {};
    var CONFIG = {"hostname":"cheney822.gitee.io","root":"/","version":"1.8.14","typing":{"enable":true,"typeSpeed":70,"cursorChar":"_","loop":false},"anchorjs":{"enable":true,"element":"h1,h2,h3,h4,h5,h6","placement":"right","visible":"hover","icon":""},"progressbar":{"enable":true,"height_px":3,"color":"#29d","options":{"showSpinner":false,"trickleSpeed":100}},"copy_btn":true,"image_zoom":{"enable":true,"img_url_replace":["",""]},"toc":{"enable":true,"headingSelector":"h1,h2,h3,h4,h5,h6","collapseDepth":1},"lazyload":{"enable":true,"loading_img":"/img/loading.gif","onlypost":false,"offset_factor":2},"web_analytics":{"enable":false,"baidu":null,"google":null,"gtag":null,"tencent":{"sid":null,"cid":null},"woyaola":null,"cnzz":null,"leancloud":{"app_id":null,"app_key":null,"server_url":null,"path":"window.location.pathname","ignore_local":false}},"search_path":"/local-search.xml"};
  </script>
  <script  src="/js/utils.js" ></script>
  <script  src="/js/color-schema.js" ></script>
<meta name="generator" content="Hexo 5.4.1"></head>


<body>
  <header style="height: 70vh;">
    <nav id="navbar" class="navbar fixed-top  navbar-expand-lg navbar-dark scrolling-navbar">
  <div class="container">
    <a class="navbar-brand" href="/">
      <strong>Cheney Blog</strong>
    </a>

    <button id="navbar-toggler-btn" class="navbar-toggler" type="button" data-toggle="collapse"
            data-target="#navbarSupportedContent"
            aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
      <div class="animated-icon"><span></span><span></span><span></span></div>
    </button>

    <!-- Collapsible content -->
    <div class="collapse navbar-collapse" id="navbarSupportedContent">
      <ul class="navbar-nav ml-auto text-center">
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/">
                <i class="iconfont icon-home-fill"></i>
                首页
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/archives/">
                <i class="iconfont icon-archive-fill"></i>
                归档
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/categories/">
                <i class="iconfont icon-category-fill"></i>
                分类
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/tags/">
                <i class="iconfont icon-tags-fill"></i>
                标签
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/about/">
                <i class="iconfont icon-user-fill"></i>
                关于
              </a>
            </li>
          
        
        
          <li class="nav-item" id="search-btn">
            <a class="nav-link" target="_self" href="javascript:;" data-toggle="modal" data-target="#modalSearch" aria-label="Search">
              &nbsp;<i class="iconfont icon-search"></i>&nbsp;
            </a>
          </li>
        
        
          <li class="nav-item" id="color-toggle-btn">
            <a class="nav-link" target="_self" href="javascript:;" aria-label="Color Toggle">&nbsp;<i
                class="iconfont icon-dark" id="color-toggle-icon"></i>&nbsp;</a>
          </li>
        
      </ul>
    </div>
  </div>
</nav>

    <div class="banner" id="banner" parallax=true
         style="background: url('https://imgbed.cheney.cc/Blog_config/default.png') no-repeat center center;
           background-size: cover;">
      <div class="full-bg-img">
        <div class="mask flex-center" style="background-color: rgba(0, 0, 0, 0.3)">
          <div class="page-header text-center fade-in-up">
            <span class="h2" id="subtitle" title="请求分页系统中的置换算法(FIFO、LRU、Optimal)">
              
            </span>

            
              <div class="mt-3">
  
  
    <span class="post-meta">
      <i class="iconfont icon-date-fill" aria-hidden="true"></i>
      <time datetime="2021-05-05 08:22" pubdate>
        2021年5月5日 早上
      </time>
    </span>
  
</div>

<div class="mt-1">
  
    <span class="post-meta mr-2">
      <i class="iconfont icon-chart"></i>
      6.3k 字
    </span>
  

  
    <span class="post-meta mr-2">
      <i class="iconfont icon-clock-fill"></i>
      
      
      32 分钟
    </span>
  

  
  
</div>

            
          </div>

          
        </div>
      </div>
    </div>
  </header>

  <main>
    
      

<div class="container-fluid nopadding-x">
  <div class="row nomargin-x">
    <div class="d-none d-lg-block col-lg-2"></div>
    <div class="col-lg-8 nopadding-x-md">
      <div class="container nopadding-x-md" id="board-ctn">
        <div class="py-5" id="board">
          <article class="post-content mx-auto">
            <!-- SEO header -->
            <h1 style="display: none">请求分页系统中的置换算法(FIFO、LRU、Optimal)</h1>
            
            <div class="markdown-body">
              <h2 id="背景"><a href="#背景" class="headerlink" title="背景"></a>背景</h2><ol>
<li>先进先出（FIFO）页面置换算法<br>该算法总是淘汰最新进入内存的页面，即选择在内存中驻留时间最久的页面予以淘汰。该算法实现简单，只需把一个进程已调入内存的页面，按先后次序链接成一个队列，并设置一个指针，称为替换指针，使它总是指向最老的页面。</li>
<li>最近最久未使用（LRU）页面置换算法<br>最近最久未使用（LRU）页面置换算法，是根据页面调入内存后的使用情况进行决策的。由于无法预测各页面将来的使用情况，只能利用“最近的过去”作为“最近的将来”的近似， 因此，LRU 置换算法是选择最近最久未使用的页面予以淘汰。该算法赋予每个页面一个访问字段，用来记录一个页面自上次被访问以来所经历的时间 t，当需淘汰一个页面时，选择现有页面中其 t 值最大的，即最近最久未使用的页面予以淘汰。</li>
<li>最佳（Optimal）页面置换算法<br>该算法选择的被淘汰页面，将是以后永远不使用的，或许是在最长（未来）时间内不再被访问的页面。采用该算法，通常可保证获得最低的缺页率。但由于人们目前还无法预知一个进程在内存的若干个页面中，哪一个页面是未来最长时间内不再被访问的，因而该算法是无法实现的，但可以利用该算法去评价其他算法。<h2 id="题目描述：请求分页系统中的置换算法"><a href="#题目描述：请求分页系统中的置换算法" class="headerlink" title="题目描述：请求分页系统中的置换算法"></a>题目描述：请求分页系统中的置换算法</h2></li>
</ol>
<h4 id="1-通过如下方法产生一指令序列，共-320-条指令。"><a href="#1-通过如下方法产生一指令序列，共-320-条指令。" class="headerlink" title="1.通过如下方法产生一指令序列，共 320 条指令。"></a>1.通过如下方法产生一指令序列，共 320 条指令。</h4><ul>
<li>A. 在[1，32k-2]的指令地址之间随机选取一起点M,访问 M；</li>
<li>B. 顺序访问M+1；</li>
<li>C. 在[0，M-1]中随机选取M1，访问 M1；</li>
<li>D. 顺序访问M1+1；</li>
<li>E. 在[M1+2，32k-2]中随机选取M2，访问 M2；</li>
<li>F. 顺序访问M2+1；</li>
<li>G. 重复 A—F，直到执行 320 次指令。</li>
<li>H.指令序列变换成页地址流设：（1）页面大小为 1K；（2）用户虚存容量为 32K。</li>
</ul>
<h4 id="2-计算并输出下述各种算法在不同内存页块-页块个数范围-8-32-下的命中率。"><a href="#2-计算并输出下述各种算法在不同内存页块-页块个数范围-8-32-下的命中率。" class="headerlink" title="2. 计算并输出下述各种算法在不同内存页块(页块个数范围:8-32)下的命中率。"></a>2. 计算并输出下述各种算法在不同内存页块(页块个数范围:8-32)下的命中率。</h4><ul>
<li>A. 先进先出（FIFO）页面置换算法</li>
<li>B. 最近最久未使用（LRU）页面置换算法</li>
<li>C. 最佳（Optimal）页面置换算法<h4 id="提示："><a href="#提示：" class="headerlink" title="提示："></a>提示：</h4></li>
<li>A.命中率=1-页面失效次数/页地址流长度</li>
<li>B.本实验中，页地址流长度为 320，页面失效次数为每次访问相应指令时，该指令所对应的页不在内存的次数。<h2 id="算法设计"><a href="#算法设计" class="headerlink" title="算法设计"></a>算法设计</h2><h4 id="整体设计"><a href="#整体设计" class="headerlink" title="整体设计"></a>整体设计</h4>设置全局变量保存指令的个数和指令数组，在<code> make_instruct()</code>函数中生成随机数填充这个数组。<br>内存这里用链表来组织，表示如下：</li>
</ul>
<figure class="highlight cpp"><table><tr><td class="gutter"><div class="code-wrapper"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></div></td><td class="code"><pre><code class="hljs cpp"><span class="hljs-keyword">struct</span> <span class="hljs-title class_">node</span> &#123;<br>    <span class="hljs-type">int</span> instruct = <span class="hljs-number">0</span>;<br>    <span class="hljs-type">int</span> time = <span class="hljs-number">0</span>;<br>    node* next = <span class="hljs-literal">NULL</span>;<br>&#125;;<br></code></pre></td></tr></table></figure>
<p>instruct表示指令号，time在不同算法中有具体含义。<br>三种算法对于三个函数，每个函数都是如：<code>double f(int a);</code>的格式，其中参数表示当前内存块大小（8-32），返回值是命中率。<br>主函数只需对不同的内存块大小调用三个函数并输出结果即可。</p>
<h4 id="产生指令序列"><a href="#产生指令序列" class="headerlink" title="产生指令序列"></a>产生指令序列</h4><p>首先写一个函数生成给定范围内的一个随机数，由于需要连续获得多个随机数，这里先在main函数srand一个种子，然后不断调用函数即可。</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><code class="hljs cpp"><span class="hljs-built_in">srand</span>((<span class="hljs-type">unsigned</span> <span class="hljs-type">int</span>)<span class="hljs-built_in">time</span>(<span class="hljs-literal">NULL</span>));<br><span class="hljs-function"><span class="hljs-type">int</span> <span class="hljs-title">rand</span><span class="hljs-params">(<span class="hljs-type">int</span> min, <span class="hljs-type">int</span> max)</span><span class="hljs-comment">//产生指定范围[min,max]的随机数。</span></span><br><span class="hljs-function"></span>&#123;<br>    <span class="hljs-keyword">return</span> <span class="hljs-built_in">rand</span>() % (max - min + <span class="hljs-number">1</span>) + min;<br>&#125;<br></code></pre></td></tr></table></figure>
<p>构造指令序列，只需要简单的按照题目要求一步步做并且循环即可，注意这里只在循环开始处有一次判断，而每次循环会产生6个指令，所以这里将指令数组开大了一点，省去了多次判断。<br><code>const int instruct_num = 320; int instruct_arr[instruct_num + 6];</code><br>另外，为了输出结果的美观用<code>cout &lt;&lt; setw(8) </code>设置输出的宽度以对齐。</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><code class="hljs cpp"><br><span class="hljs-function"><span class="hljs-type">void</span> <span class="hljs-title">make_instruct</span><span class="hljs-params">()</span> </span>&#123;<span class="hljs-comment">//产生指令序列</span><br>    <span class="hljs-type">int</span> n = <span class="hljs-number">0</span>;<br>    <span class="hljs-keyword">while</span> (n &lt; instruct_num) &#123;<br>        <span class="hljs-type">int</span> M = <span class="hljs-built_in">rand</span>(<span class="hljs-number">1</span>,<span class="hljs-number">30</span>);<br>        instruct_arr[n++] = M;<br>        instruct_arr[n++] = M + <span class="hljs-number">1</span>;<br>        <span class="hljs-type">int</span> M1 = <span class="hljs-built_in">rand</span>(<span class="hljs-number">0</span>, M - <span class="hljs-number">1</span>);<br>        instruct_arr[n++] = M1;<br>        instruct_arr[n++] = M1 + <span class="hljs-number">1</span>;<br>        <span class="hljs-type">int</span> M2 = <span class="hljs-built_in">rand</span>(M1 + <span class="hljs-number">2</span>, <span class="hljs-number">30</span>);<br>        instruct_arr[n++] = M2;<br>        instruct_arr[n++] = M2 + <span class="hljs-number">1</span>;<br>    &#125;<br>&#125;<br></code></pre></td></tr></table></figure>

<h4 id="先进先出（FIFO）"><a href="#先进先出（FIFO）" class="headerlink" title="先进先出（FIFO）"></a>先进先出（FIFO）</h4><p>这是最基础的，以下的算法都继承这种思想，只是用于淘汰的策略有所变化。<br>首先新建两个节点<code>Head</code>和<code>Tail</code>Head为头节点，其数据域<code>Head-&gt;instruct</code>表示当前内存中实际有多少被占用，其next指向第一块被占用的内存。Tail为尾指针，指向内存的尾部。<br>算法首先是一层循环，遍历所有的（320个）指令。对于每个指令判断是否在内存中，若在则<code>hit</code>置为1。如果在内存中则不做任何操作，不在则要让<code>failure_times</code>加一，然后判断内存是否被占满，若未被占满则直接加入链表，若被占用则要淘汰当前队列中的一个指令，并将当前指令插入内存的合适位置。<br>这里用到的淘汰算法：先进先出，即找到最先进来的即可，这里我是每次插入到链表尾，故链表头是最先进来的，所以每次都删除链表头后面的第一个指令并将新指令加到链表尾即可，注意每次更新Tail的位置。</p>
<h4 id="最近最久未使用（LRU）"><a href="#最近最久未使用（LRU）" class="headerlink" title="最近最久未使用（LRU）"></a>最近最久未使用（LRU）</h4><p>这里只介绍与FIFO不同之处。</p>
<ul>
<li>设立一个变量<code>clock</code>表示时钟，初始值为999，主循环一次clock就减1.</li>
<li>如果当前指令在内存中则将其时间刷新为当前的时钟。</li>
<li>淘汰算法：遍历内存队列找到time最大的，将其替换为新的节点即可，新加入的节点time为当前时钟clock<h4 id="最佳（Optimal）"><a href="#最佳（Optimal）" class="headerlink" title="最佳（Optimal）"></a>最佳（Optimal）</h4></li>
<li>淘汰算法：每次遍历内存队列，对于每个指令，再次遍历全部指令集，找到将来还要多久这条指令会再被执行（下一个出现的位置减去当前位置）。<h2 id="代码实现"><a href="#代码实现" class="headerlink" title="代码实现"></a>代码实现</h2></li>
</ul>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br><span class="line">114</span><br><span class="line">115</span><br><span class="line">116</span><br><span class="line">117</span><br><span class="line">118</span><br><span class="line">119</span><br><span class="line">120</span><br><span class="line">121</span><br><span class="line">122</span><br><span class="line">123</span><br><span class="line">124</span><br><span class="line">125</span><br><span class="line">126</span><br><span class="line">127</span><br><span class="line">128</span><br><span class="line">129</span><br><span class="line">130</span><br><span class="line">131</span><br><span class="line">132</span><br><span class="line">133</span><br><span class="line">134</span><br><span class="line">135</span><br><span class="line">136</span><br><span class="line">137</span><br><span class="line">138</span><br><span class="line">139</span><br><span class="line">140</span><br><span class="line">141</span><br><span class="line">142</span><br><span class="line">143</span><br><span class="line">144</span><br><span class="line">145</span><br><span class="line">146</span><br><span class="line">147</span><br><span class="line">148</span><br><span class="line">149</span><br><span class="line">150</span><br><span class="line">151</span><br><span class="line">152</span><br><span class="line">153</span><br><span class="line">154</span><br><span class="line">155</span><br><span class="line">156</span><br><span class="line">157</span><br><span class="line">158</span><br><span class="line">159</span><br><span class="line">160</span><br><span class="line">161</span><br><span class="line">162</span><br><span class="line">163</span><br><span class="line">164</span><br><span class="line">165</span><br></pre></td><td class="code"><pre><code class="hljs cpp"><span class="hljs-meta">#<span class="hljs-keyword">include</span> <span class="hljs-string">&lt;iostream&gt;</span></span><br><span class="hljs-meta">#<span class="hljs-keyword">include</span> <span class="hljs-string">&lt;time.h&gt;</span></span><br><span class="hljs-meta">#<span class="hljs-keyword">include</span> <span class="hljs-string">&lt;iomanip&gt;</span></span><br><span class="hljs-keyword">using</span> <span class="hljs-keyword">namespace</span> std;<br><br><span class="hljs-type">const</span> <span class="hljs-type">int</span> instruct_num = <span class="hljs-number">320</span>;<br><span class="hljs-type">int</span> instruct_arr[instruct_num + <span class="hljs-number">6</span>];<br><span class="hljs-keyword">struct</span> <span class="hljs-title class_">node</span> &#123;<br>    <span class="hljs-type">int</span> instruct = <span class="hljs-number">0</span>;<br>    <span class="hljs-type">int</span> time = <span class="hljs-number">0</span>;<br>    node* next = <span class="hljs-literal">NULL</span>;<br>&#125;;<br><span class="hljs-function"><span class="hljs-type">int</span> <span class="hljs-title">rand</span><span class="hljs-params">(<span class="hljs-type">int</span> min, <span class="hljs-type">int</span> max)</span><span class="hljs-comment">//产生指定范围[min,max]的随机数。</span></span><br><span class="hljs-function"></span>&#123;<br>    <span class="hljs-keyword">return</span> <span class="hljs-built_in">rand</span>() % (max - min + <span class="hljs-number">1</span>) + min;<br>&#125;<br><span class="hljs-function"><span class="hljs-type">void</span> <span class="hljs-title">make_instruct</span><span class="hljs-params">()</span> </span>&#123;<span class="hljs-comment">//产生指令序列</span><br>    <span class="hljs-type">int</span> n = <span class="hljs-number">0</span>;<br>    <span class="hljs-keyword">while</span> (n &lt; instruct_num) &#123;<br>        <span class="hljs-type">int</span> M = <span class="hljs-built_in">rand</span>(<span class="hljs-number">1</span>,<span class="hljs-number">30</span>);<br>        instruct_arr[n++] = M;<br>        instruct_arr[n++] = M + <span class="hljs-number">1</span>;<br>        <span class="hljs-type">int</span> M1 = <span class="hljs-built_in">rand</span>(<span class="hljs-number">0</span>, M - <span class="hljs-number">1</span>);<br>        instruct_arr[n++] = M1;<br>        instruct_arr[n++] = M1 + <span class="hljs-number">1</span>;<br>        <span class="hljs-type">int</span> M2 = <span class="hljs-built_in">rand</span>(M1 + <span class="hljs-number">2</span>, <span class="hljs-number">30</span>);<br>        instruct_arr[n++] = M2;<br>        instruct_arr[n++] = M2 + <span class="hljs-number">1</span>;<br>    &#125;<br>&#125;<br><span class="hljs-function"><span class="hljs-type">double</span> <span class="hljs-title">C_FIFO</span><span class="hljs-params">(<span class="hljs-type">int</span> block_size)</span> </span>&#123;<br>    <span class="hljs-type">int</span> failure_times = <span class="hljs-number">0</span>;<br>    node* Head = <span class="hljs-keyword">new</span> node;<br>    node* Tail = Head;<br>    <span class="hljs-keyword">for</span> (<span class="hljs-type">int</span> i = <span class="hljs-number">0</span>; i &lt; instruct_num; i++) &#123;<br>        <span class="hljs-type">int</span> cur_instruct = instruct_arr[i];<br>        <span class="hljs-type">int</span> hit = <span class="hljs-number">0</span>;<br>       <br>        <span class="hljs-keyword">for</span> (node* p = Head-&gt;next; p != <span class="hljs-literal">NULL</span>; p = p-&gt;next)<br>            <span class="hljs-keyword">if</span> (p-&gt;instruct == cur_instruct)<br>                hit = <span class="hljs-number">1</span>;<br><br>        <span class="hljs-keyword">if</span> (!hit)&#123;<br>            failure_times++;<br>            <span class="hljs-keyword">if</span> (Head-&gt;instruct &gt;= block_size) <span class="hljs-comment">//内存已满</span><br>                Head-&gt;next = Head-&gt;next-&gt;next;                       <br>            <span class="hljs-keyword">else</span> <br>                Head-&gt;instruct++;             <br>            <br>            Tail-&gt;next = <span class="hljs-keyword">new</span> node;<br>            Tail = Tail-&gt;next;<br>            Tail-&gt;instruct = cur_instruct;<br>            Tail-&gt;next = <span class="hljs-literal">NULL</span>;<br>        &#125;<br>    &#125;<br><br>    <span class="hljs-keyword">return</span> <span class="hljs-number">1.0</span> - (<span class="hljs-type">double</span>)failure_times / instruct_num;<br>&#125;<br><span class="hljs-function"><span class="hljs-type">double</span> <span class="hljs-title">C_LRU</span><span class="hljs-params">(<span class="hljs-type">int</span> block_size)</span> </span>&#123;<br>    <span class="hljs-type">int</span> failure_times = <span class="hljs-number">0</span>;<br>    node* Head = <span class="hljs-keyword">new</span> node;<br>    node* Tail = Head;<br>    <span class="hljs-type">int</span> clock = <span class="hljs-number">999</span>;<br><br>    <span class="hljs-keyword">for</span> (<span class="hljs-type">int</span> i = <span class="hljs-number">0</span>; i &lt; instruct_num; i++) &#123;<br>        clock--;<br>        <span class="hljs-type">int</span> cur_instruct = instruct_arr[i];<br>        <span class="hljs-type">int</span> hit = <span class="hljs-number">0</span>;<br>        <span class="hljs-keyword">for</span> (node* p = Head-&gt;next; p != <span class="hljs-literal">NULL</span>; p = p-&gt;next)<br>            <span class="hljs-keyword">if</span> (p-&gt;instruct == cur_instruct) &#123;<br>                hit = <span class="hljs-number">1</span>;<br>                p-&gt;time = clock;<span class="hljs-comment">//刷新时钟</span><br>            &#125;<br>       <br>        <span class="hljs-keyword">if</span> (!hit) &#123;<br>            failure_times++;<br>            <span class="hljs-keyword">if</span> (Head-&gt;instruct &gt;= block_size) &#123; <span class="hljs-comment">//内存已满</span><br>                node* t = <span class="hljs-keyword">new</span> node; t-&gt;time = <span class="hljs-number">-1</span>;<br>                <span class="hljs-keyword">for</span> (node* p = Head-&gt;next; p != <span class="hljs-literal">NULL</span>; p = p-&gt;next)<span class="hljs-comment">//遍历找到最久未使用的</span><br>                    <span class="hljs-keyword">if</span> (p-&gt;time &gt; t-&gt;time)<br>                        t = p;<br>                <br>                t-&gt;instruct = cur_instruct;<br>                t-&gt;time = clock;<br>      <br>            &#125;<br>            <span class="hljs-keyword">else</span> &#123;<br>                Head-&gt;instruct++;<br>                Tail-&gt;next = <span class="hljs-keyword">new</span> node;<br>                Tail = Tail-&gt;next;<br>                Tail-&gt;instruct = cur_instruct;<br>                Tail-&gt;time = clock;<br>                Tail-&gt;next = <span class="hljs-literal">NULL</span>;<br>            &#125;<br>        &#125;<br>    &#125;<br>    <span class="hljs-keyword">return</span> <span class="hljs-number">1.0</span> - (<span class="hljs-type">double</span>)failure_times / instruct_num;<br>&#125;<br><span class="hljs-function"><span class="hljs-type">double</span> <span class="hljs-title">C_Optimal</span><span class="hljs-params">(<span class="hljs-type">int</span> block_size)</span> </span>&#123;<br>    <span class="hljs-type">int</span> failure_times = <span class="hljs-number">0</span>;<br>    node* Head = <span class="hljs-keyword">new</span> node;<br>    node* Tail = Head;<br>    <span class="hljs-keyword">for</span> (<span class="hljs-type">int</span> i = <span class="hljs-number">0</span>; i &lt; instruct_num; i++) &#123;<br>        <span class="hljs-type">int</span> cur_instruct = instruct_arr[i];<br>        <span class="hljs-type">int</span> hit = <span class="hljs-number">0</span>;<br><br>        <span class="hljs-keyword">for</span> (node* p = Head-&gt;next; p != <span class="hljs-literal">NULL</span>; p = p-&gt;next)<br>            <span class="hljs-keyword">if</span> (p-&gt;instruct == cur_instruct)<br>                hit = <span class="hljs-number">1</span>;<br><br>        <span class="hljs-keyword">if</span> (!hit) &#123;<br>            failure_times++;<br>            <span class="hljs-keyword">if</span> (Head-&gt;instruct &gt;= block_size) &#123; <span class="hljs-comment">//内存已满</span><br>                <span class="hljs-comment">//找到每个请求还有多久会被用到</span><br>                <span class="hljs-keyword">for</span> (node* p = Head-&gt;next; p != <span class="hljs-literal">NULL</span>; p = p-&gt;next) &#123;<br>                    p-&gt;time = <span class="hljs-number">999</span>;<br>                    <span class="hljs-keyword">for</span> (<span class="hljs-type">int</span> j = i + <span class="hljs-number">1</span>; j &lt; instruct_num; j++)<br>                        <span class="hljs-keyword">if</span> (p-&gt;instruct == instruct_arr[i]) &#123;<br>                            p-&gt;time = j - i;<br>                            <span class="hljs-keyword">break</span>;<br>                        &#125;                 <br>                &#125;<br>                <span class="hljs-comment">//找到最久不被用到的淘汰</span><br>                node* t = <span class="hljs-keyword">new</span> node; t-&gt;time = <span class="hljs-number">-1</span>;<br>                <span class="hljs-keyword">for</span> (node* p = Head-&gt;next; p != <span class="hljs-literal">NULL</span>; p = p-&gt;next)<span class="hljs-comment">//遍历找到最久未使用的</span><br>                    <span class="hljs-keyword">if</span> (p-&gt;time &gt; t-&gt;time)<br>                        t = p;<br><br>                t-&gt;instruct = cur_instruct;<br><br>            &#125;<br>            <span class="hljs-keyword">else</span> &#123;<br>                Head-&gt;instruct++;<br>                Tail-&gt;next = <span class="hljs-keyword">new</span> node;<br>                Tail = Tail-&gt;next;<br>                Tail-&gt;instruct = cur_instruct;<br>                Tail-&gt;next = <span class="hljs-literal">NULL</span>;<br>            &#125;        <br>        &#125;<br>    &#125;<br>    <span class="hljs-keyword">return</span> <span class="hljs-number">1.0</span> - (<span class="hljs-type">double</span>)failure_times / instruct_num;;<br>&#125;<br><span class="hljs-function"><span class="hljs-type">int</span> <span class="hljs-title">main</span><span class="hljs-params">()</span></span><br><span class="hljs-function"></span>&#123;<br>    <span class="hljs-built_in">srand</span>((<span class="hljs-type">unsigned</span> <span class="hljs-type">int</span>)<span class="hljs-built_in">time</span>(<span class="hljs-literal">NULL</span>));<br>    <span class="hljs-built_in">make_instruct</span>();<br>    <br>    cout &lt;&lt; <span class="hljs-string">&quot;指令序列为：&quot;</span> &lt;&lt; endl;<br>    <span class="hljs-type">int</span> i = <span class="hljs-number">0</span>;<br>    <span class="hljs-keyword">while</span> (i++ &lt; instruct_num) &#123;<br>        cout &lt;&lt; instruct_arr[i] &lt;&lt; <span class="hljs-string">&quot;\t&quot;</span>;<br>        <span class="hljs-keyword">if</span> (i % <span class="hljs-number">20</span> == <span class="hljs-number">0</span>)cout &lt;&lt; endl;<br>    &#125;cout &lt;&lt; endl &lt;&lt; endl;<br><br>    cout &lt;&lt; <span class="hljs-string">&quot;SIZE\t\t&quot;</span> &lt;&lt; <span class="hljs-string">&quot;FIFO\t\t&quot;</span> &lt;&lt; <span class="hljs-string">&quot;LRU\t\t&quot;</span> &lt;&lt; <span class="hljs-string">&quot;Optimal&quot;</span> &lt;&lt; endl;<br>    <span class="hljs-keyword">for</span> (<span class="hljs-type">int</span> disk_block_size = <span class="hljs-number">8</span>; disk_block_size &lt;= <span class="hljs-number">32</span>; disk_block_size++) &#123;<br><br>        cout &lt;&lt; disk_block_size &lt;&lt; <span class="hljs-string">&quot;\t&quot;</span>;<br>        cout &lt;&lt; <span class="hljs-built_in">setw</span>(<span class="hljs-number">8</span>) &lt;&lt; <span class="hljs-built_in">C_FIFO</span>(disk_block_size) &lt;&lt; <span class="hljs-string">&quot;\t&quot;</span>;<br>        cout &lt;&lt; <span class="hljs-built_in">setw</span>(<span class="hljs-number">8</span>) &lt;&lt; <span class="hljs-built_in">C_LRU</span>(disk_block_size) &lt;&lt; <span class="hljs-string">&quot;\t&quot;</span>;<br>        cout &lt;&lt; <span class="hljs-built_in">setw</span>(<span class="hljs-number">8</span>) &lt;&lt; <span class="hljs-built_in">C_Optimal</span>(disk_block_size) &lt;&lt; <span class="hljs-string">&quot;\t&quot;</span>;<br>        cout &lt;&lt; endl;<br><br>    &#125;<br>&#125;<br></code></pre></td></tr></table></figure>

<h2 id="运行结果"><a href="#运行结果" class="headerlink" title="运行结果"></a>运行结果</h2><p><img src="https://imgbed.cheney.cc/picgo/20210506173120425.png" srcset="/img/loading.gif" lazyload alt="在这里插入图片描述"></p>
<p><img src="https://imgbed.cheney.cc/picgo/20210506173024754.png" srcset="/img/loading.gif" lazyload alt="在这里插入图片描述"></p>

            </div>
            <hr>
            <div>
              <div class="post-metas mb-3">
                
                  <div class="post-meta mr-3">
                    <i class="iconfont icon-category"></i>
                    
                      <a class="hover-with-bg" href="/categories/%E6%93%8D%E4%BD%9C%E7%B3%BB%E7%BB%9F/">操作系统</a>
                    
                  </div>
                
                
                  <div class="post-meta">
                    <i class="iconfont icon-tags"></i>
                    
                      <a class="hover-with-bg" href="/tags/%E7%AE%97%E6%B3%95/">算法</a>
                    
                      <a class="hover-with-bg" href="/tags/C%E8%AF%AD%E8%A8%80/">C语言</a>
                    
                  </div>
                
              </div>
              
                <p class="note note-warning">
                  
                    本博客所有文章除特别声明外，均采用 <a target="_blank" href="https://creativecommons.org/licenses/by-sa/4.0/deed.zh" rel="nofollow noopener noopener">CC BY-SA 4.0 协议</a> ，转载请注明出处！
                  
                </p>
              
              
                <div class="post-prevnext">
                  <article class="post-prev col-6">
                    
                    
                      <a href="/2021/05/06/%E6%93%8D%E4%BD%9C%E7%B3%BB%E7%BB%9F__%E8%BF%9B%E7%A8%8B%E9%80%9A%E4%BF%A1%E7%9A%84%E4%B8%89%E7%A7%8D%E6%96%B9%E5%BC%8F%EF%BC%88%E7%AE%A1%E9%81%93%E3%80%81%E6%B6%88%E6%81%AF%E7%BC%93%E5%86%B2%E9%98%9F%E5%88%97%E3%80%81%E5%85%B1%E4%BA%AB%E7%BC%93%E5%86%B2%E5%8C%BA%EF%BC%89/">
                        <i class="iconfont icon-arrowleft"></i>
                        <span class="hidden-mobile">进程通信的三种方式（管道、消息缓冲队列、共享缓冲区）</span>
                        <span class="visible-mobile">上一篇</span>
                      </a>
                    
                  </article>
                  <article class="post-next col-6">
                    
                    
                      <a href="/2021/05/04/%E6%93%8D%E4%BD%9C%E7%B3%BB%E7%BB%9F__%E5%A4%9A%E7%BA%A7%E9%98%9F%E5%88%97%E8%B0%83%E5%BA%A6%E5%92%8C%E5%A4%9A%E7%BA%A7%E5%8F%8D%E9%A6%88%E9%98%9F%E5%88%97%E8%B0%83%E5%BA%A6%E7%AE%97%E6%B3%95%E7%9A%84%E5%AE%9E%E7%8E%B0/">
                        <span class="hidden-mobile">多级队列调度和多级反馈队列调度算法的实现</span>
                        <span class="visible-mobile">下一篇</span>
                        <i class="iconfont icon-arrowright"></i>
                      </a>
                    
                  </article>
                </div>
              
            </div>

            
          </article>
        </div>
      </div>
    </div>
    
      <div class="d-none d-lg-block col-lg-2 toc-container" id="toc-ctn">
        <div id="toc">
  <p class="toc-header"><i class="iconfont icon-list"></i>&nbsp;目录</p>
  <div class="toc-body" id="toc-body"></div>
</div>

      </div>
    
  </div>
</div>

<!-- Custom -->


    

    
      <a id="scroll-top-button" aria-label="TOP" href="#" role="button">
        <i class="iconfont icon-arrowup" aria-hidden="true"></i>
      </a>
    

    
      <div class="modal fade" id="modalSearch" tabindex="-1" role="dialog" aria-labelledby="ModalLabel"
     aria-hidden="true">
  <div class="modal-dialog modal-dialog-scrollable modal-lg" role="document">
    <div class="modal-content">
      <div class="modal-header text-center">
        <h4 class="modal-title w-100 font-weight-bold">搜索</h4>
        <button type="button" id="local-search-close" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body mx-3">
        <div class="md-form mb-5">
          <input type="text" id="local-search-input" class="form-control validate">
          <label data-error="x" data-success="v"
                 for="local-search-input">关键词</label>
        </div>
        <div class="list-group" id="local-search-result"></div>
      </div>
    </div>
  </div>
</div>
    

    
  </main>

  <footer class="text-center mt-5 py-3">
  <div class="footer-content">
     <a href="https://hexo.io" target="_blank" rel="nofollow noopener"><span>Hexo</span></a> <i class="iconfont icon-love"></i> <a href="https://cheney822.gitee.io/" target="_blank" rel="nofollow noopener"><span>备用网址</span></a> 
  </div>
  

  
  <!-- 备案信息 -->
  <div class="beian">
    <span>
      <a href="http://beian.miit.gov.cn/" target="_blank" rel="nofollow noopener">
        皖ICP备2022002876号-1
      </a>
    </span>
    
  </div>


  
</footer>


  <!-- SCRIPTS -->
  
  <script  src="https://cdn.jsdelivr.net/npm/nprogress@0/nprogress.min.js" ></script>
  <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/nprogress@0/nprogress.min.css" />

  <script>
    NProgress.configure({"showSpinner":false,"trickleSpeed":100})
    NProgress.start()
    window.addEventListener('load', function() {
      NProgress.done();
    })
  </script>


<script  src="https://cdn.jsdelivr.net/npm/jquery@3/dist/jquery.min.js" ></script>
<script  src="https://cdn.jsdelivr.net/npm/bootstrap@4/dist/js/bootstrap.min.js" ></script>
<script  src="/js/events.js" ></script>
<script  src="/js/plugins.js" ></script>

<!-- Plugins -->


  <script  src="/js/local-search.js" ></script>



  
    <script  src="/js/img-lazyload.js" ></script>
  



  



  
    <script  src="https://cdn.jsdelivr.net/npm/tocbot@4/dist/tocbot.min.js" ></script>
  
  
    <script  src="https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@3/dist/jquery.fancybox.min.js" ></script>
  
  
    <script  src="https://cdn.jsdelivr.net/npm/anchor-js@4/anchor.min.js" ></script>
  
  
    <script defer src="https://cdn.jsdelivr.net/npm/clipboard@2/dist/clipboard.min.js" ></script>
  






  <script  src="https://cdn.jsdelivr.net/npm/typed.js@2/lib/typed.min.js" ></script>
  <script>
    (function (window, document) {
      var typing = Fluid.plugins.typing;
      var title = document.getElementById('subtitle').title;
      
        typing(title);
      
    })(window, document);
  </script>















<!-- 主题的启动项 保持在最底部 -->
<script  src="/js/boot.js" ></script>


</body>
</html>
